package com.rectcircle.scalatrateset.controller

import com.rectcircle.scalatrateset.model.User

// JSON相关库
import org.json4s.{DefaultFormats, Formats}

// 来自Scalatra的JSON处理支持
import org.scalatra.json._
/**
  * @author Rectcircle
  *         createTime 2017/1/6
  */
class JsonController extends ScalatratestStack with JacksonJsonSupport{
	
	//设置自动case类到JSON输出序列化，需要JValueResult trait。
	protected implicit lazy val jsonFormats: Formats = DefaultFormats
	
	// 在每个操作运行之前，将内容类型设置为JSON格式。
	before() {
		contentType = formats("json")
	}
	
	get("/caseClass"){
		User(1,"u1","123")
	}
	
	get("/caseClassList"){
		List(
			User(1,"u1","123"),
			User(2,"u2","456")
		)
	}
	
	get("/complexJson"){
		Map(
			"errcode" -> 0,
			"errmsg" -> "success",
			"data" -> Map(
				"userList" -> List(
					User(1,"u1","123"),
					User(2,"u2","456")
				),
				"status" -> 0
			)
		)
	}
	
	post("/create"){
		println(request.body)
		val u = parsedBody.extract[User]
		println(u)
		println(u.name)
		u
	}
}


